package com.wgb.movie.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wgb.movie.annotation.AuthCheck;
import com.wgb.movie.common.BaseResponse;
import com.wgb.movie.common.DeleteRequest;
import com.wgb.movie.common.ErrorCode;
import com.wgb.movie.common.ResultUtils;
import com.wgb.movie.constant.UserConstant;
import com.wgb.movie.exception.BusinessException;
import com.wgb.movie.exception.ThrowUtils;
import com.wgb.movie.mapper.MovieOrderMapper;
import com.wgb.movie.model.dto.movieShow.MovieShowAddRequest;
import com.wgb.movie.model.dto.movieShow.MovieShowEditRequest;
import com.wgb.movie.model.dto.movieShow.MovieShowQueryRequest;
import com.wgb.movie.model.dto.movieShow.MovieShowUpdateRequest;
import com.wgb.movie.model.entity.HotMovie;
import com.wgb.movie.model.entity.MovieShow;
import com.wgb.movie.model.entity.SeatStatus;
import com.wgb.movie.model.entity.User;
import com.wgb.movie.model.vo.HotMovieVO;
import com.wgb.movie.model.vo.MovieShowVO;
import com.wgb.movie.model.vo.MovieVO;
import com.wgb.movie.service.MovieShowService;
import com.wgb.movie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 上映接口
 */
@RestController
@RequestMapping("/movieShow")
@Slf4j
public class MovieShowController {

    @Resource
    private MovieShowService movieShowService;

    @Resource
    private UserService userService;



    // region 增删改查


    /**
     * 创建上映
     *
     * @param movieShowAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addMovieShow(@RequestBody MovieShowAddRequest movieShowAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(movieShowAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        MovieShow movieShow = new MovieShow();
        BeanUtils.copyProperties(movieShowAddRequest, movieShow);
        // 数据校验
        movieShowService.validMovieShow(movieShow, true);
        movieShowAddRequest.setSeats(SeatStatus.generateSeats(10, 10));
        // todo 填充默认值
        movieShow.setSeats(JSONUtil.toJsonStr(movieShowAddRequest.getSeats()));
        // 写入数据库
        boolean result = movieShowService.save(movieShow);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newMovieShowId = movieShow.getId();
        return ResultUtils.success(newMovieShowId);
    }

    /**
     * 删除上映
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteMovieShow(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        MovieShow oldMovieShow = movieShowService.getById(id);
        ThrowUtils.throwIf(oldMovieShow == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = movieShowService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新上映（仅管理员可用）
     *
     * @param movieShowUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateMovieShow(@RequestBody MovieShowUpdateRequest movieShowUpdateRequest) {
        if (movieShowUpdateRequest == null || movieShowUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        MovieShow movieShow = new MovieShow();
        BeanUtils.copyProperties(movieShowUpdateRequest, movieShow);
        // 数据校验
        movieShowService.validMovieShow(movieShow, false);
        // 判断是否存在
        long id = movieShowUpdateRequest.getId();
        MovieShow oldMovieShow = movieShowService.getById(id);
        ThrowUtils.throwIf(oldMovieShow == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = movieShowService.updateById(movieShow);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取上映（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<MovieShowVO> getMovieShowVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        MovieShow movieShow = movieShowService.getById(id);
        ThrowUtils.throwIf(movieShow == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(movieShowService.getMovieShowVO(movieShow, request));
    }

    /**
     * 分页获取上映列表（仅管理员可用）
     *
     * @param movieShowQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MovieShow>> listMovieShowByPage(@RequestBody MovieShowQueryRequest movieShowQueryRequest) {
        long current = movieShowQueryRequest.getCurrent();
        long size = movieShowQueryRequest.getPageSize();
        // 查询数据库
        Page<MovieShow> movieShowPage = movieShowService.page(new Page<>(current, size),
                movieShowService.getQueryWrapper(movieShowQueryRequest));
        return ResultUtils.success(movieShowPage);
    }

    /**
     * 分页获取上映列表（封装类）
     *
     * @param movieShowQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<MovieShowVO>> listMovieShowVOByPage(@RequestBody MovieShowQueryRequest movieShowQueryRequest,
                                                                 HttpServletRequest request) {
        long current = movieShowQueryRequest.getCurrent();
        long size = movieShowQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<MovieShow> movieShowPage = movieShowService.page(new Page<>(current, size),
                movieShowService.getQueryWrapper(movieShowQueryRequest));
        // 获取封装类
        return ResultUtils.success(movieShowService.getMovieShowVOPage(movieShowPage, request));
    }

    /**
     * 分页获取当前登录用户创建的上映列表
     *
     * @param movieShowQueryRequest
     * @param request
     * @return
     */
//    @PostMapping("/my/list/page/vo")
//    public BaseResponse<Page<MovieShowVO>> listMyMovieShowVOByPage(@RequestBody MovieShowQueryRequest movieShowQueryRequest,
//                                                                   HttpServletRequest request) {
//        ThrowUtils.throwIf(movieShowQueryRequest == null, ErrorCode.PARAMS_ERROR);
//        // 补充查询条件，只查询当前登录用户的数据
//        User loginUser = userService.getLoginUser(request);
//        movieShowQueryRequest.setUserId(loginUser.getId());
//        long current = movieShowQueryRequest.getCurrent();
//        long size = movieShowQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        // 查询数据库
//        Page<MovieShow> movieShowPage = movieShowService.page(new Page<>(current, size),
//                movieShowService.getQueryWrapper(movieShowQueryRequest));
//        // 获取封装类
//        return ResultUtils.success(movieShowService.getMovieShowVOPage(movieShowPage, request));
//    }

    /**
     * 编辑上映（给用户使用）
     *
     * @param movieShowEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editMovieShow(@RequestBody MovieShowEditRequest movieShowEditRequest, HttpServletRequest request) {
        if (movieShowEditRequest == null || movieShowEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        MovieShow movieShow = new MovieShow();
        BeanUtils.copyProperties(movieShowEditRequest, movieShow);
        // 数据校验
        movieShowService.validMovieShow(movieShow, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = movieShowEditRequest.getId();
        MovieShow oldMovieShow = movieShowService.getById(id);
        ThrowUtils.throwIf(oldMovieShow == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = movieShowService.updateById(movieShow);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }



    // endregion
}
